import { AppDataSource } from './data.source'
import { User } from './entity/User'
import { Role } from './entity/Role'

// 多对多
// 比如：一个用户可以分配多个角色，一个角色可以分配给多个用户
AppDataSource.initialize().then(async () => {

    const userRepository = AppDataSource.getRepository(User);

    const roleRepository = AppDataSource.getRepository(Role);

    let datestr3 = String(+new Date());
    let laststr3 = Number(datestr3.split('').splice(datestr3.length - 4, datestr3.length - 1).join(''));
    const role1 = new Role()
    role1.role = '管理员nosave' + laststr3
    // await roleRepository.save(role1)

    const role2 = new Role();
    role2.role = '局长nosave' + laststr3
    // await roleRepository.save(role2)

    const user1 = new User();
    let datestr1 = String(+new Date());
    let laststr1 = Number(datestr1.split('').splice(datestr1.length - 4, datestr1.length - 1).join(''));
    user1.age = parseInt(String(laststr1 / 100));
    user1.email = datestr1 + '@qq.com';
    user1.firstName = 'firstName:' + laststr1;
    user1.lastName = 'lastName:' + laststr1;
    user1.roles = [role1, role2];
    await userRepository.save(user1);

    const user2 = new User();
    let datestr2 = String(+new Date());
    let laststr2 = Number(datestr2.split('').splice(datestr2.length - 4, datestr2.length - 1).join(''));
    user2.age = parseInt(String(laststr2 / 100));
    user2.email = datestr2 + '@qq.com';
    user2.firstName = 'firstName:' + laststr2;
    user2.lastName = 'lastName:' + laststr2;
    user2.roles = [role1, role2];
    await userRepository.save(user2);


    // 查询所有用户及其角色
    const usersWithRoles = await userRepository.find({
        relations: ["roles"], // 明确加载关联的 roles 数据
    });

    // 查询单个用户及其角色
    const user = await userRepository.findOne({
        where: { id: 1 },
        relations: ["roles"],
    });
    console.log(usersWithRoles);
    console.log(user);
    
}).finally(() => {
    process.exit();
})